package com.zz.hhbl.interceptor

import com.zz.framework.core.ext.getAppVersion
import com.zz.framework.core.utils.DeviceUtils
import com.zz.framework.core.utils.language.LanguageManager
import com.zz.hhbl.config.GlobalCache
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject


/**
 * Copyright © 2020 zanezhao All rights reserved.
 * Created on 2020/3/26 12:45 PM.
 * @version: V1.0
 */
object CommonBodyParameterInterceptor {
    fun builder(): Interceptor {
        return Interceptor { chain ->
            val commonBodyMap = hashMapOf(
                "code" to DeviceUtils.getSerialCode(),
                "version" to getAppVersion(),
                "lang" to LanguageManager.currentLangCode
            )
            var request = chain.request()
            if (request.method == "POST") {
                request.body?.let { body ->
                    request = when {
                        body is FormBody -> {
                            // 构建新的 FormBody，并添加公共参数
                            val newFormBody = FormBody.Builder().apply {
                                for (i in 0 until body.size) {
                                    addEncoded(body.encodedName(i), body.encodedValue(i))
                                }
                                commonBodyMap.forEach { (key, value) ->
                                    addEncoded(key, value)
                                }
                            }.build()
                            request.newBuilder().post(newFormBody).build()
                        }
                        body.contentType()?.subtype == "json" -> {
                            // 读取原 JSON
                            val buffer = okio.Buffer().also { body.writeTo(it) }
                            val originalJson = buffer.readUtf8()
                            // 解析 JSON 并添加公共参数
                            val jsonObject = JSONObject(originalJson).apply {
                                if (request.url.encodedPath != "/loginDevice") {
                                    commonBodyMap.forEach { (key, value) -> put(key, value) }
                                }
                            }
                            // 创建新的 RequestBody
                            val newBody = jsonObject.toString()
                                .toRequestBody("application/json".toMediaTypeOrNull())
                            request.newBuilder().method(request.method, newBody).build()
                        }
                        else -> request
                    }
                }
            }
            chain.proceed(request)
        }
    }
}